package main.app.model.http
{	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;


	public class HttpService extends EventDispatcher
	{
		private var _url:String;//服务器路径
		private var _data:Object;//服务器 的数据
		private var _requestData:String;//请求的命名数据
		
		public function HttpService(url:String,requestData:String="")
		{
			_url = url;
			_requestData = requestData;
			
			if(_requestData != "")
			{
				reuqestServer(_requestData);
			}
		}
		/**
		 *请求服务器 
		 * @param data 传输的数据
		 * 
		 */		
		public function reuqestServer(requestData:String):void
		{
			//创建URLLoader对象
			var urlLoader:URLLoader = new URLLoader();                
			//设置接收数据方式(文本、原始二进制数据、URL 编码变量);
			urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
			//设置传递参数
			var urlVars:URLVariables = new URLVariables();
			urlVars.data =  requestData;
			//建立Request访问对象
			var urlRequest:URLRequest = new URLRequest(_url);
			//设置参数
			urlRequest.data = urlVars;
			//设置访问模式(POST,GET)
			urlRequest.method = URLRequestMethod.POST;
			
			try
			{
				urlLoader.load(urlRequest);
			}
			catch(error:Error)
			{
				trace(error)
			}
			
			//加载完成
			urlLoader.addEventListener(Event.COMPLETE, urlLoaderCompleteHandler);
			//开始访问
			urlLoader.addEventListener(Event.OPEN, urlLoaderOpenHandler);
			//加载进度
			urlLoader.addEventListener(ProgressEvent.PROGRESS, urlLoaderProgressHandler);
			//跨域访问安全策略
			urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, urlLoaderSecurityErrorHandler);
			//Http状态事件
			urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, urlLoaderHttpStatusHandler);    
			//访问出错事件
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, urlLoaderIoErrorHandler);        
		}
		private function urlLoaderCompleteHandler(e:Event):void
		{   
			_data = e.target.data;
			this.dispatchEvent(e);
		}
		
		private function urlLoaderOpenHandler(e:Event):void
		{
			this.dispatchEvent(e);
		}
		
		private function urlLoaderProgressHandler(e:ProgressEvent):void
		{
			this.dispatchEvent(e);
		}
		
		private function urlLoaderSecurityErrorHandler(e:SecurityErrorEvent):void
		{
			this.dispatchEvent(e);
		}
		
		private function urlLoaderHttpStatusHandler(e:HTTPStatusEvent):void
		{
			this.dispatchEvent(e);
		}
		
		private function urlLoaderIoErrorHandler(e:IOErrorEvent):void
		{
			this.dispatchEvent(e);
		}

		public function get url():String
		{
			return _url;
		}

		public function set url(value:String):void
		{
			_url = value;
		}

		public function get data():Object
		{
			return _data;
		}


	}
	
}